package com.example.assign2_list;

import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyCountries extends ListActivity {
	public static ArrayList<TodoTask> countryList = new ArrayList<TodoTask>();
	public static TasksDataSource dbDataSource;
	public static ListView listView;
	public static ArrayAdapter<TodoTask> adapt;
	
	private static boolean sorted;
	private static String backgroundColor;
	private static SharedPreferences prefs;
	private static String topPad;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbDataSource = new TasksDataSource(this);
        dbDataSource.open();
        countryList = dbDataSource.getAllTasks();
        
    	/*	setup ListAdapter	*/
    	int row_ID = android.R.layout.simple_list_item_1;
    	adapt = new ArrayAdapter<TodoTask>(this, row_ID, countryList);
    	setListAdapter(adapt);

    	/*	Config ListView	*/
    	listView = getListView();
    	listView.setTextFilterEnabled(true);
    	listView.setOnItemClickListener(new ItemClick());
    	registerForContextMenu(listView);
    	
    	prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	
    	backgroundColor = prefs.getString("backgroundColor", "1");
    	if(backgroundColor.equals("1")){
    		listView.setBackgroundColor(Color.WHITE); }
    	else if(backgroundColor.equals("2"))
    	{ listView.setBackgroundColor(Color.GREEN); }
    	else if(backgroundColor.equals("3"))
    	{ listView.setBackgroundColor(Color.RED); }
    	else { listView.setBackgroundColor(Color.BLUE); }
    	
    	topPad = prefs.getString("padTop", "1");
    	if(topPad.equals("1")){
    		listView.setPadding(0, 0, 0, 0); }
    	else if(topPad.equals("2")){
    		listView.setPadding(0, 100, 0, 0); }
    	else if(topPad.equals("3")){
    		listView.setPadding(0, 200, 0, 0); }
    	
    	sorted = prefs.getBoolean("sorted", true);
    	sortList(sorted);
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	
    	/*	Load backgroundColor, default is white	*/
    	backgroundColor = prefs.getString("backgroundColor", "1");
    	if(backgroundColor.equals("1")){
    		listView.setBackgroundColor(Color.WHITE); }
    	else if(backgroundColor.equals("2")){ 
    		listView.setBackgroundColor(Color.GREEN);
    	}
    	else if(backgroundColor.equals("3"))
    	{ listView.setBackgroundColor(Color.RED); }
    	else { listView.setBackgroundColor(Color.BLUE); }
    	
    	/* Load topPadding, defualt is 0*/
    	topPad = prefs.getString("padTop", "1");
    	if(topPad.equals("1")){
    		listView.setPadding(0, 0, 0, 0); }
    	else if(topPad.equals("2")){
    		listView.setPadding(0, 100, 0, 0); }
    	else if(topPad.equals("3")){
    		listView.setPadding(0, 200, 0, 0); }
    	
    	/*	Load properties if list is sorted, default is sorted by year */
    	sorted = prefs.getBoolean("sorted", true);
    	sortList(sorted);
    }
    
    @Override
    public void onStop(){
    	super.onStop();
    	
    	SharedPreferences.Editor editor = prefs.edit();
    	
    	/* Save backgroundColor properties	*/
    	editor.putString("backgroundColor", backgroundColor);
    	
    	/* Save padding properties	*/
    	editor.putString("padTop", topPad);
    	
    	/*	Get latest sort preferences and save */
    	editor.putBoolean("sorted", sorted);
    	
    	//	Save the new preferences
    	editor.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mycountry_main_menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
    	switch (item.getItemId()) {
        	case R.id.add_country: 
        		/*	Start AddCountry activity */
        		Intent addCountryIntent = new Intent(this, AddCountry.class);
            	startActivity(addCountryIntent);
        		return true;
        	case R.id.sort_by_year:
        		sorted = true;
        		sortList(sorted);
        		return true;
        	case R.id.sort_by_country:
        		sorted = false;
        		sortList(sorted);
        		return true;
        	case R.id.preference:
        		Intent prefIntent = new Intent(this, Preferences.class);
        		startActivity(prefIntent);
        		return true;
        	default:
                return super.onOptionsItemSelected(item);
    	}
    }
    
    /* Sort list by year or Country (true if year, false if country) */
    private void sortList(boolean sortYearorCountry){
    	if(sortYearorCountry){
    		adapt.clear();
    		countryList = dbDataSource.sortBy("year");
    		adapt.addAll(countryList);
    	}
    	else{
    		adapt.clear();
    		countryList = dbDataSource.sortBy("countries");
    		adapt.addAll(countryList);
    	}
    }
    
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
    	super.onCreateContextMenu(menu, v, menuInfo);  
    	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    	/*	set title to task	*/
    	menu.setHeaderTitle(countryList.get(info.position).toString());
    	/*	add items to menu	*/
    	menu.add(0, 0, 0, "Update");  
    	menu.add(0, 1, 0, "Delete");  
    }
    
    @Override  
    public boolean onContextItemSelected(MenuItem item) {  
    	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        /*	check wich item is selected	*/
    	if(item.getItemId() == 0)	//	Update task
    	{
    		TodoTask task = countryList.get(info.position);
        	int updateYear = dbDataSource.getTask(task.getId()).getYear();
        	String updateCountry = dbDataSource.getTask(task.getId()).getCountry();
        	
        	/*	Start UpdateCountry activity and send information to intent	 */
    		Intent intent = new Intent(this, UpdateCountry.class);
    		intent.putExtra("taskId", task.getId());
    		intent.putExtra("year", updateYear);
    		intent.putExtra("country", updateCountry);
        	startActivity(intent);
        }  
        else if(item.getItemId() == 1)	// Delete task
        {
        	TodoTask task = countryList.get(info.position);
        	dbDataSource.deleteTask(task);
        	adapt.remove(task);
        }  
        else {
        	return false;
        }  
    return true;  
    }  
    
    private class ItemClick implements OnItemClickListener {
    	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    	/* Present selected country as a toast */
    	CharSequence str = ((TextView) view).getText();
    	Toast.makeText(MyCountries.this, str, Toast.LENGTH_SHORT).show();
    	}
    } 
}